class MyPageHeader extends BaseEditMaster {
    constructor(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
            returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl) {
        super(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
                returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl);
    }
    // 得到领料单数据
    GetEntityData() {
        let item = {};
        item['headerId'] = $("#HeaderId").val();
        item['billNo'] = $.trim($("#BillNo").val());
        item['productId'] = $.trim($("#StyleNo").val());
        item['processingContractId'] = $("#ProcessingContractId").val();
        item['requisitionUnit'] = $("#RequisitionUnit").val();
        item['description'] = formatNullInputValue($.trim($("#Description").val()));  // 备注
        item['createdBy'] = $.trim($("#UserId").val());
        item['updatedBy'] = $.trim($("#UserId").val());
        return item;
        //return JSON.stringify(item);
    }
    FillData(data) {
        let item = data.HeaderEntity;
        $("#HeaderId").val(item.headerId);
        $("#BillNo").val(item.billNo);
        $("#ProcessingContractId").val(item.processingContractId);
        $("#ProcessingContractNo").val(item.processingContractNo);
        $("#RequisitionUnit").val(item.requisitionUnit);
        $("#RequisitionUnitName").val(item.requisitionUnitName);
        $("#StyleNo").html('<option value="' + item.productId + '">' + item.styleNo + '</option>');
        $("#Description").val(item.description);
        $("#UpdatedByName").val(item.updatedByName);
        $("#UpdatedDate").val(formatNullData(item.updatedDate));
        $("#IcLabDipIndication").val(item.icLabDipIndication);
        $("#EmbroideryLaceAndOther").val(item.embroideryLaceAndOther);

        // 最后的审核人、审核日期
        $("#CheckedBy").val(item.checkedBy);
        $("#CheckedByName").val(item.checkedByName);
        $("#CheckedDate").val(item.checkedDate === null ? '' : item.checkedDate);
        $("#CheckedStatus").val(item.checkedStatus);
        $('#FlowOrderNo').val(item.flowOrderNo);

        // 显示明细数据
        _InstancePageLines.BuildDataTable(data.LinesList);

        this.currentTaskPrivileges = item.currentTaskPrivileges;
        this.nextTaskPrivileges = item.nextTaskPrivileges;
        this.unCheckFlag = item.unCheckFlag;
        this.SetPageElementStatus(this.HidePageElement, this.ShowPageElement, function () {
            _InstancePageLines.AutoAdjustTableHeightForLines();
        });

        $("#BillNo").focus();
    }
    Save() {
        //step 1、进行页面验证，失败则返回
        if (!$("#form_data").valid())
            return;

        if (this.pageStatus === 1) {
            super.DoAjax(this.GetEntityData(), "/manufacture/requisition_slip/header/save.html", function (data, _this) {
                if (data.Key !== undefined) {
                    $("#HeaderId").val(data.Key);   // 设置刚才插入的记录ID
                    _this.dataId = data.Key;
                    $("#Action").val(2);
                    _this.pageStatus = 2;
                    $("#panelSlave").show();
                    _InstancePageLines.BuildDataTable(data.LinesList);
                    ShowSuccessMessagePanel("新增成功。");
                }
            });
        } else {
            super.DoAjax(this.GetEntityData(), "/manufacture/requisition_slip/header/update.html", function (data, _this) {
                ShowSuccessMessagePanel("更新成功。");
            });
        }
    }
    New() {
        super.New();
        this.FetchNewBillNo();

        // 默认设置一些值
        $("#HeaderId").val(0);
        $("#ChoiceProcessingContract").show();
        $("#StyleNo").html('<option value="-1">-- 请选择 --</option>');
        $("#UpdatedByName").val($("#UserName").val());
        $("#UpdatedDate").val(getCurrentDate());

        this.pageStatus = 1;
        $("#panelSlave").hide();
        $('#tabData11 tbody').empty();
        $('#tabData12 tbody').empty();
        //this.rows = 0;
        //自适应高度
        //_InstancePageLines.AutoAdjustTableHeightForLines();
        $("#BillNo").focus();
    }
    FetchNewBillNo() {
        super.DoAjax(null, "/manufacture/requisition_slip/header/fetchNewBillNo.html", function (data, $self) {
            $("#BillNo").val(data.BillNo);
        });
    }
    // 得到明细数据列表信息
    FetchLinesByHeaderKey() {
        $.ajax({
            type: "POST",
            url: parent.basePath + "/manufacture/requisition_slip/lines/fetchLinesByHeaderKey.html",
            timeout: 30 * 1000,
            data: JSON.stringify($("#HeaderId").val()),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
            }
        }).done(function (data) {
            _InstancePageLines.BuildDataTable(data);

            //    page_status = 2;      // 将状态由增加 -> 编辑
            $("#SlaveArea").show();
        }).fail(function (data) {
            ajaxError(data, 1);
        }).always(function () {
        });
    }
    // 选择加工合同号
    DoChoiceProcessingContract() {
        let _choice = new CommonChoice();
        _choice.DoChoiceProcessingContract(0, '选择加工合同', (data) => {
            if (data) {
                // 判断是否数据发生了改变如果改变则设置改变标记
                if ($("#ProcessingContractNo").val() !== data[1]) {
                    $("#form_data").data("changed", true);
                }
                $("#ProcessingContractId").val(data[0]);
                $("#ProcessingContractNo").val(data[1]);
                $("#RequisitionUnit").val(data[2]);
                $("#RequisitionUnitName").val(data[3]);
                $("#ProcessingContractNo").focus();
                // 设置款号
                _InstancePageHeader.SetStyleNo(data[0]);
            }
        });
        $("#ProcessingContractNo").focus();
    }
    // 根据加工合同标识，设置款号
    SetStyleNo(processingContractHeaderId) {
        super.DoAjax(processingContractHeaderId, "/manufacture/cpc/header/fetchStyleNoByHeaderKey.html", function (data, $self) {
            if (data !== null) {
                $("#StyleNo").empty();
                let options = [];
                options.push('<option value="-1">-- 请选择 --</option>');
                for (let i = 0; i < data.length; i++) {
                    options.push('<option value="', data[i].productId, '">', data[i].styleNo, '</option>');
                }
                $("#StyleNo").html(options.join(''));
            } else {
                ShowErrorMessagePanel('该合同没有款号信息。');
            }
        });
    }
    // 应该根据款号找到对应的单耗表，然后在备注处做成下拉列表供用户选择（因为同一款有多个单耗表，用备注进行区分）
    DoChoiceStyleNo() {
        // 根据款号得到单耗表中的IC色样指示和刺绣花边和其他物品单耗，显示在画面中
        let _params = {};
        _params['StyleNo'] = $("#StyleNo").find("option:selected").text();
        _params['TypeFlag'] = '0';    // 单耗类型 0：正常 1：副资材
        // >>> 应该根据款号找到对应的调达，然后从调达中找到单耗表，从而得到相应的IC色样指示等信息。
        // >>> 这个地方直接根据款号从单耗取是有问题的
        super.DoAjax(_params, "/tech/piece_yardage_onesize/fetchByStyleNo.html", function (data, $self) {
            if (data !== null && data.length > 0) {
                $("#IC_ColourSampleIndication").val(data[0].icLabDipIndication === null ? "" : data[0].icLabDipIndication);
                $("#EmbroideryLaceAndOther").val(data[0].embroideryLaceAndOther === null ? "" : data[0].embroideryLaceAndOther);
            } else {
                $("#IC_ColourSampleIndication").val("");
                $("#EmbroideryLaceAndOther").val("");
            }
        });
    }
    DoPrintPreview() {
        // 得到要打印的内容
        let str = "";   //$("#tabData11 tbody").html();
        let str2 = ""; // $("#tabData12 tbody").html();
        $('#tabData11 tbody').find("tr").eq(0);
        $('#tabData11 tbody tr').each(function () {
            let row = $(this).index();

            let $tr1 = $(this);
            let $tr2 = $('#tabData12 tbody').find("tr").eq(row);
            str += "<tr>" + $tr1.html() + $tr2.html() + "</tr>";
        });

        let _print_content =
                '<table style="width:100%; margin:0 auto; text-align:left;">' +
                '<colgroup>' +
                '             <col style="width: 7%;" />' +
                '             <col style="width: 17%;" />' +
                '              <col style="width: 7%;" />' +
                '             <col style="width: 17%;" />' +
                '              <col style="width: 7%;" />' +
                '              <col style="width: 17%;" />' +
                '               <col style="width: 7%;" />' +
                '               <col />' +
                '</colgroup>' +
                '<tbody>' +
                ' <tr><td colspan="8" style="font-size:16px; font-weight:bold; padding-bottom:10px; border: none;">领料单</td></tr>' +
                '<tr><td>领料单号:' + '</td><td>' + $("#BillNo").val() + '</td>' +
                '<td>加工合同号:' + '</td><td>' + $("#ProcessingContractNo").val() + '</td>' +
                '<td>款号:' + '</td><td>' + $("#StyleNo").find("option:selected").text() + '</td>' +
                '<td>领料单位:' + '</td><td>' + $("#RequisitionUnitName").val() + '</td></tr>' +
                '<tr><td >备注:' + '</td><td colspan="7">' + $("#Description").val() + '</td></tr>' +
                '<tr><td>IC色样指示:' + '</td><td>' + $("#IC_ColourSampleIndication").val() + '</td>' +
                '<td>刺绣花边及其他物品单耗:' + '</td><td>' + $("#EmbroideryLaceAndOther").val() + '</td>' +
                '<td>操作情况:' + '</td><td>' + $("#UpdatedByName").val() + $("#UpdatedDate").val() + '</td>' +
                '<td>审核情况:' + '</td><td>' + $("#CheckedByName").val() + $("#CheckedDate").val() + '</td></tr>' +
                '    </tbody></table>' +
                '<table style="width:100%;position:relative;top:5px; margin:0 auto; text-align:left;">' +
                '    <thead>' +
                '        <tr>' +
                '            <th></th>' +
                '            <th>供应商</th>' +
                '            <th>原料名称</th>' +
                '            <th>用料部位</th>' +
                '            <th>品号</th>' +
                '            <th>成品数</th>' +
                '            <th>生产浮动增量</th>' +
                '            <th>套裁数</th>' +
                '            <th>规格/CM</th>' +
                '            <th>单位</th>' +
                '            <th>成品颜色</th> ' +
                '            <th>工厂单用量</th> ' +
                '            <th>生产单用量</th> ' +
                '            <th>套裁单用量</th> ' +
                '            <th>净幅(单耗)</th> ' +
                '            <th>材料颜色</th> ' +
                '            <th>材料规格</th> ' +
                '            <th>必要数</th> ' +
                '            <th>生产必要数</th> ' +
                '            <th>套裁数量</th> ' +
                '            <th>补给数</th> ' +
                '            <th>备注</th> ' +
                '        </tr>' +
                '    </thead>' +
                '    <tbody>' + str +
                '    </tbody></table>';

        // 生成并打印ifrme  
        let _iframe = document.createElement('IFRAME');
        _iframe.setAttribute('style', 'position:absolute; width:0px; height:0px; left:-500px; top:-500px;');
        document.body.appendChild(_iframe);
        let _doc = _iframe.contentWindow.document;
        _doc.write('<!DOCTYPE html>');
        _doc.write('<html><head><meta charset="utf-8">');
        // 引入打印的专有CSS样式
        _doc.write('<style type="text/css" media="print">' +
                '    @page {' +
                '        size: A4 landscape;' +
                //'    margin: 10mm 10mm 10mm 10mm;' +
                '        @bottom-right {font-size:9pt; content: "页 " counter(page) " / " counter(pages);}' +
                '    }' +
                '    table {border-collapse: collapse; border-spacing: 0;}' +
                '    thead {display: table-header-group;}' +
                '    th {padding: 3px 2px; font-size: 12px; font-weight: bold; text-align: center; border: 1px solid #000;}' +
                '    td {padding: 3px 2px; font-size: 12px; font-weight: normal; text-align: center; border: 1px solid #000;}' +
                '</style>');
        _doc.write('</head><body>');
        _doc.write(_print_content);
        _doc.write('</body></html>');
        _doc.close();
        _iframe.contentWindow.print();
        document.body.removeChild(_iframe);
        // window.open(parent.basePath + "/printpreview/manufacture/requisitionSheet.html");
    }
    ExportToExcel() {
        showModal(585, 278, '导出生产领料单', parent.basePath + '/popup/manufacture/requisitionSheet/exportOption.html', null, null);
    }
    // 审核控制 checkedFlag 是否有审核权
    SetCheckStatus(checkedBy) {
        if (checkedBy === null) {   // 未审核(如果有审核权限，隐藏反审按钮，显示审核按钮)
            if ($("#ActionAcl_6").length > 0 || parseInt($("#ActionAcl_6").val() === 1)) {  // 有审核权限
                $("#ButCheck").show();
                $("#ButUnCheck").hide();
            } else {
                $("#ButCheck").hide();
                $("#ButUnCheck").hide();
            }

            $("#ButCheck").show();
            $("#ButUnCheck").hide();
            $("#ButUpdate").show();
            $("#ButPrintPreview").hide();
            $("#slaveBtnPanel").show();
            $("#CheckedBy").val("");
            $("#CheckedByName").val("");
            $("#CheckedDate").val("");
        } else {                    // 已审核(如果有反审核权限，隐藏审核按钮，显示反审按钮)
            if ($("#ActionAcl_7").length > 0 || parseInt($("#ActionAcl_7").val() === 1)) {  // 有反审核权限
                $("#ButCheck").hide();
                $("#ButUnCheck").show();
            } else {
                $("#ButCheck").hide();
                $("#ButUnCheck").hide();
            }
            // 锁住更新（主从表）
            $("#ButUpdate").hide();
            $("#slaveBtnPanel").hide();
            $("#ButPrintPreview").show();
        }

        if (checkedBy !== null) {  // 审核
            $("#IsChecked").removeClass().addClass("n1");
            $("#IsChecked").html("状态：已审核。");

            $('#tabData11 tbody tr').find("td span").removeClass("trash");
            $('#tabData11 tbody tr').find("td span i").removeClass("fa-all fa-trash-o fa-1");
        } else {                  // 未审核               
            $("#IsChecked").removeClass().addClass("n2");
            $("#IsChecked").html("状态：未审核。");

            $('#tabData11 tbody tr').find("td span").addClass("trash");
            $('#tabData11 tbody tr').find("td span i").addClass("fa-all fa-trash-o fa-1");
        }
    }
    DoCheck() {
        super.DoCheck(function (data, $self) {
            // 显示明细数据
            _InstancePageLines.BuildDataTable(data.LinesList);
            // 设置画面各个元素状态
            $self.SetPageElementStatus($self.HidePageElement, $self.ShowPageElement, function () {
                _InstancePageLines.AutoAdjustTableHeightForLines();
            });
        });
    }
    Uncheck() {
        super.Uncheck(function (data, $self) {
            // 显示明细数据
            _InstancePageLines.BuildDataTable(data.LinesList);
            // 设置画面各个元素状态
            $self.SetPageElementStatus($self.HidePageElement, $self.ShowPageElement, function () {
                _InstancePageLines.AutoAdjustTableHeightForLines();
            });
        });
    }
    ShowPageElement() {
        $("Button.act__save").show();
        if (!$("span.act__delete").hasClass("act__delete")) {
            $("span.act__delete").addClass("trash");
            $("span.act__delete i").addClass("fa-all fa-trash-o fa-1");
        }
    }
    HidePageElement() {
        $("Button.act__save").hide();
        $("span.act__delete").removeClass("trash");
        $("span.act__delete i").removeClass("fa-all fa-trash-o fa-1");
    }
    Expand() {
        super.Expand(function () {
            // 自适应高度
            _InstancePageLines.AutoAdjustTableHeightForLines();
        });
    }
    Collapse() {
        super.Collapse(function () {
            // 自适应高度
            _InstancePageLines.AutoAdjustTableHeightForLines();
        });
    }
}

//------------------------------------------------------------------------------
// 明细处理部分
//------------------------------------------------------------------------------
class MyPageLines extends BaseEditSlave {
    constructor() {
        super('', '', '');
    }
    BuildDataTable(result) {
        $('#tabData11 tbody').empty();
        $('#tabData12 tbody').empty();
        // 得到数据列表
        if (result === null || result.length === 0) {
            $("#panelSlave").show();
            this.rows = 0;
            // 自适应高度
            this.AutoAdjustTableHeightForLines();
            return false;
        }
        let content01 = '';
        let content02 = '';
        this.rows = result.length;
        this.numCheckbox = result.length;
        for (let i = 0; i < result.length; i++) {
            let id = result[i].linesId;
            let _trCss = '';
            if (parseInt(result[i].quoteFlag) !== 0) {
                _trCss = 'class="quotedRow"';
            }
            content01 += '<tr _mash_id="' + id + '" ' + _trCss + '>';
            //      if ($("#CheckedByName").val() !== "") {
            //           content01 += '<td><span title="删除"  onclick="linesHandler.DoDelete(\'' + id + '\');"><i></i></span></td>';
            //       } else {
            content01 += '<td class="column__action"><span title="删除" class="trash act__delete" onclick="_InstancePageLines.DeleteLines($(this));"><i class="fa-all fa-trash-o fa-1"></i></span></td>';
            //        }
            content01 += '<td>' + formatNullData(result[i].supplierName) + '</td>';
            content01 += '<td>' + formatNullData(result[i].materialName) + '</td>';
            content01 += '<td >' + formatNullData(result[i].partOfNeed) + '</td>';
            content01 += '<td >' + formatNullData(result[i].materialCode) + '</td>';
            content01 += '</tr>';

            content02 += '<tr _mash_id="' + id + '">';
            content02 += '<td>' + formatNullData(result[i].productQuantity) + '</td>';
            content02 += '<td class="edited-cell">' + formatNullData(result[i].floatingIncrement === 0 ? null : result[i].floatingIncrement) + '</td>';
            content02 += '<td>' + formatNullData(result[i].suitCutQuantity === 0 ? null : result[i].suitCutQuantity) + '</td>';
            content02 += '<td>' + formatNullData(result[i].productSizeName) + '</td>';   // specification 此处为成品码 可是 却写着规格
            content02 += '<td style="text-align:center;">' + formatNullData(result[i].uomName) + '</td>';
            content02 += '<td>' + formatNullData(result[i].productColourName) + '</td>';
            content02 += '<td>' + formatNullData(result[i].f_PieceYardage === 0 ? null : result[i].f_PieceYardage) + '</td>';
            content02 += '<td class="edited-cell">' + formatNullData(result[i].seamPieceYardage === 0 ? null : result[i].seamPieceYardage) + '</td>';
            content02 += '<td>' + formatNullData(result[i].s_PieceYardage === 0 ? null : result[i].s_PieceYardage) + '</td>';
            content02 += '<td>' + formatNullData(result[i].fabricWidth) + '</td>';
            content02 += '<td>' + formatNullData(result[i].materialColourName) + '</td>';
            content02 += '<td>' + formatNullData(result[i].specification) + '</td>';          // 规格 
            content02 += '<td>' + formatNullData(result[i].mrpPlanQuantity) + '</td>';        // 调达表中的必要数
            let _mrpFactoryQuantity = (result[i].productQuantity + result[i].floatingIncrement) * result[i].seamPieceYardage;
            content02 += '<td>' + formatNullData(_mrpFactoryQuantity === 0 ? null : _mrpFactoryQuantity.toFixed(2)) + '</td>';              // 生产必要数
            content02 += '<td>' + formatNullData(result[i].suitCutQuantity === 0 ? null : result[i].suitCutQuantity.toFixed(2)) + '</td>';  // 套裁数量
            content02 += '<td>' + formatNullData(result[i].mrpRealQuantity === 0 ? null : result[i].mrpRealQuantity) + '</td>';             // 补给数（调达表中）
            content02 += '<td class="edited-cell">' + formatNullData(result[i].description) + '</td>';    //
            content02 += '</tr>';
            $('#tabData11 tbody').append(content01);
            $('#tabData12 tbody').append(content02);
            content01 = '';
            content02 = '';
        }
        setTwoTableRowColor("tabData11", "tabData12");
        
        // 设置明细部分高度
        this.AutoAdjustTableHeightForLines();

        let _cellid = "_cell__field";
        let _cellname = "__cell__field";
        $('#tabData12 tbody tr').find("td.edited-cell").click(function () {
            OnCellClickEvent($(this), _cellid, _cellname, 0);
        });
    }
    GetLinesData() {
        let jsonResult = [];
        //得到修改过数据
        $('#tabData12 tbody').find("tr").each(function () {
            let $tr2 = $(this);
            if ($tr2.find("td.dirty").length) {
                let item = {};
                item['headerId'] = $("#HeaderId").val();    // 返回明细使用
                item['linesId'] = $tr2.attr("_mash_id");
                item['floatingIncrement'] = formatNullInputValue($.trim($tr2.find('td').eq(1).text())) === null ? 0 : $.trim($tr2.find('td').eq(1).text());         //生产浮动增量    
                item['seamPieceYardage'] = formatNullInputValue($.trim($tr2.find('td').eq(7).text())) === null ? 0 : $.trim($tr2.find('td').eq(7).text());         //生产单用量                 

                item['description'] = formatNullInputValue($.trim($tr2.find('td').last().text()));        // 备注
                item['updatedBy'] = $("#UserId").val();
                jsonResult.push(item);
            }
        });
        return JSON.stringify(jsonResult);
    }
    SaveLines() {
        //step 1、进行页面验证，失败则返回
        let _success = CheckGridInput();
        if (!_success)
            return;

        super.SaveLines("/manufacture/requisition_slip/lines/update.html", function (data, $self) {
            if (data.Success) {
                // 刷新合同明细
                $self.BuildDataTable(data.LinesList);
                ShowSuccessMessagePanel("保存成功。");
            }
        });
    }
    // 补充明细
    Supplement() {
        // 为了防止之前修改过的内容丢失，所以要首先保存一下
        if ($('#tabData11 tbody tr').find("td.dirty").length > 0 || $('#tabData12 tbody tr').find("td.dirty").length > 0) {
            showModal(370, 140, '系统信息', '', null, null, 1, "数据有更新，是否需要保存？", () => {
                this.OnSaveLines();
            }, () => {
                return false;
            });
        } else {
            this.OnSupplement();
        }
    }
    // 补充明细记录
    OnSupplement() {
        let criterion = {};
        criterion['HeaderId'] = parseInt($("#HeaderId").val());
        criterion['ProductId'] = parseInt($("#StyleNo").val());
        criterion['UserId'] = parseInt($("#UserId").val());

        super.DoAjax(criterion, "/manufacture/requisition_slip/lines/supplement.html", (data, $self) => {
            $self.BuildDataTable(data);
            ShowSuccessMessagePanel("补充完成。");
        });
    }
    DeleteLines($self) {
        let params = {};
        params['HeaderId'] = parseInt($("#HeaderId").val());
        params['LinesId'] = $self.parent().parent().attr("_mash_id");
        params['DeletedBy'] = $.trim($("#UserId").val());

        super.DeleteLines(params, "/manufacture/requisition_slip/lines/delete.html", function (data, _this) {
            // 刷新明细
            $self.BuildDataTable(data.LinesList);
            ShowSuccessMessagePanel('删除成功。');
        });
    }
    AutoAdjustTableHeightForLines() {
        let h = $(window).height();
        let _tabTop = 0;   // 用于随着窗口变化，下面明细高度随之变化的一个节点
        if ($("#panelSlaveButton_01").css('display') === 'none') {
            _tabTop = $("#panelSlave").offset().top + 72;
        } else {
            _tabTop = $("#panelSlave").offset().top + 97;
        }
        let _rc = Math.floor((h - _tabTop - 20) / 25);
        let _dh = _rc * 25 + 17;
        let _rowH = this.rows * 25 + 17; // 计算行高
        _dh = (_rowH >= _dh) ? _dh : _rowH;

        $("#divD11").css({"max-height": _dh - 17, height: _dh - 17});
        $("#divD12").css({"max-height": _dh + 1, height: _dh + 1});

        let w = $(window).width();
        let wLeftList = 596; // 左边列表固定宽度
        $("#divH12").css({width: w - wLeftList - 17});
        $("#divD12").css({left: -1, width: w - wLeftList - 16});
    }
    ScrollTo() {
        $('#divH12').scrollLeft($('#divD12').scrollLeft());
        $('#divD11').scrollTop($('#divD12').scrollTop());
    }
}

let _InstancePageHeader = null;
let _InstancePageLines = null;

//-----------------------------------------------------------------------------
// 页面初始化
//-----------------------------------------------------------------------------
function onPageReady() {
    let _pageStatus = parseInt($("#Action").val());
    let _dataId = $("#HeaderId").val();

    let requisition_slip_list_result = $.cookie("requisition_slip_list_result") === undefined ? "" : $.cookie("requisition_slip_list_result");
    let _pageListData = [];
    if (requisition_slip_list_result !== "") {
        _pageListData = requisition_slip_list_result.split(',');
        $("#rec_total_rows").text(_pageListData.length);
        $("#rec_cur_row").text($.inArray(_dataId, _pageListData) + 1);

        if (_pageListData.length > 0) {
            let index = $.inArray(_dataId, _pageListData);
            if (index === 0) {
                $("#ButPrev").attr("disabled", "disabled");
            } else {
                $("#ButNext").removeAttr("disabled");
            }
            if (index === (_pageListData.length - 1)) {
                $("#ButNext").attr("disabled", "disabled");
            } else {
                $("#ButPrev").removeAttr("disabled");
            }
        }
    } else {
        $("#rec_total_rows").text("1");
        $("#rec_cur_row").text("1");
    }

    _InstancePageHeader = new MyPageHeader(_dataId, 0, 0, _pageStatus, _pageListData,
            "/manufacture/requisition_slip/list.html",
            "/manufacture/requisition_slip/header/fetchByKey.html",
            "/manufacture/requisition_slip/header/save.html",
            "/manufacture/requisition_slip/header/export.html",
            "/manufacture/requisition_slip/header/print.html");

    _InstancePageLines = new MyPageLines();

    $("#tabPanelHeader").wxTabs({tabContent: "tabPanelData"});
    $("#hPanelSplitter").click(function () {
        if ($(this).children("i").hasClass("fa-angle-double-up")) {
            _InstancePageHeader.Collapse();
        } else {
            _InstancePageHeader.Expand();
        }
    });

    _InstancePageHeader.OnPageLoad();
}

// 画面大小或者位置移动
function onPageResize() {
    let w = $(window).width();
    let wLeftList = 596; // 左边列表固定宽度

    $("#divH12").css({width: w - wLeftList - 17});
    $("#divD12").css({left: -1, width: w - wLeftList - 16});

    if (_InstancePageLines !== null)
        _InstancePageLines.AutoAdjustTableHeightForLines();
}

//-----------------------------------------------------------------------------
// 验证函数
//-----------------------------------------------------------------------------
$.validator.setDefaults({
    ignore: 'hidden, [reaonly=readonly]'
});
$.validator.addMethod("valueNotEquals", function (value, element, arg) {
    return arg !== value;
}, "Value must not equal arg.");

$(function () {
    $("#form_data").validate({
        // Step 1：设置验证规则和错误消息
        rules: {
            _BillNo: "required",
            _ProcessingContractNo: "required",
            _StyleNo: {
                valueNotEquals: "-1",
                required: true
            }
        },
        messages: {
            _BillNo: "请填写领料单号。",
            _ProcessingContractNo: "请填写加工合同号。",
            _StyleNo: {
                valueNotEquals: "请选择款号。",
                required: "请选择款号。"
            }
        },
        // Step 2：设置验证触发事件
        onclick: false,
        onfocusout: false,
        onfocusin: false,
        onkeyup: false,
        onkeydown: false,
        focusInvalid: false,
        // Step 3：设置错误信息提示
        showErrors: window.showErrors  //使用自定义的错误显示方法
    });
});
// 验证输入
function CheckGridInput() {
    $('#tabData12 tbody').find("tr").each(function (index) {
        let _n1 = $.trim($(this).find('td').eq(1).text()).length > 0 ? $.trim($(this).find('td').eq(1).text()) : 0; //
        let _n7 = $.trim($(this).find('td').eq(7).text()).length > 0 ? $.trim($(this).find('td').eq(7).text()) : 0; //

        if (_n1 !== 0) {
            if (!isNumber(_n1)) {
                GridCheckErrHandle($(this), 1, '请输入正确的数字。');
            } else {
                GridCheckSuccessHandle($(this), 1);
            }
        }
        if (_n7 !== 0) {
            if (!isNumber(_n7)) {
                GridCheckErrHandle($(this), 7, '请输入正确的数字。');
            } else {
                GridCheckSuccessHandle($(this), 7);
            }
        }
    });

    if ($('#tabData11 tbody').find('td.error').length > 0 || $('#tabData12 tbody').find('td.error').length > 0) {
        ShowErrorMessagePanel('对不起，填写的数据有错误。');
        return false;
    } else {
        return true;
    }
}
function GridCheckErrHandle($row, index, errMsg) {
    $row.find('td').eq(index).addClass("error");
    $row.find('td').eq(index).attr('title', errMsg);
}
function GridCheckSuccessHandle($row, index) {
    $row.find('td').eq(index).removeClass("error");
    $row.find('td').eq(index).attr('title', '');
}